package com.sunlee.common.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sunlee.common.core.entity.PageData;
import com.sunlee.common.core.exception.BusinessException;
import com.sunlee.common.core.utils.StringUtil;
import com.sunlee.common.service.dao.ProductCategoryMappingDao;
import com.sunlee.common.service.dto.CategoryDTO;
import com.sunlee.common.service.dto.ProductCategoryMappingDTO;
import com.sunlee.common.service.dto.ProductDTO;
import com.sunlee.common.service.entity.*;
import com.sunlee.common.service.enums.ThirdResStatusEnum;
import com.sunlee.common.service.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品分类映射表
 */
@Service
@Slf4j
public class ProductCategoryMappingServiceImpl extends CrudServiceImpl<ProductCategoryMappingDao, ProductCategoryMappingEntity, ProductCategoryMappingDTO> implements ProductCategoryMappingService {

    @Autowired
    private CategoryService categoryService;

    @Lazy
    @Autowired
    private ProductService productService;

    @Autowired
    private ThirdProductService thirdProductService;

    @Lazy
    @Autowired
    private ThirdProductCategoryMappingService thirdProductCategoryMappingService;

    @Autowired
    private ThirdCategoryMappingService thirdCategoryMappingService;

    @Autowired
    @Lazy
    private ProductCategoryMappingService productCategoryMappingService;

    @Override
    public PageData<ProductDTO> pageRelatedByCid(Map<String, Object> params, long id, int type, Long pId, String title) {
        IPage<ProductEntity> page = baseDao.pageRelatedByCid(getPage(params, null, false), id, type, pId, title);

        return getPageData(page, ProductDTO.class);

    }

    @Override
    public PageData<CategoryDTO> pageRelatedByPid(Map<String, Object> params, long pid) {
        PageData<CategoryDTO> thirdCategoryPage = categoryService.pageOwn(params);

        List<CategoryDTO> allCategory = thirdCategoryPage.getList();

        List<ProductCategoryMappingEntity> chooseCategory = list(new LambdaQueryWrapper<ProductCategoryMappingEntity>()
                .eq(ProductCategoryMappingEntity::getProductId, pid));

        if (CollectionUtils.isEmpty(chooseCategory)) {
            return thirdCategoryPage;
        }

        allCategory.forEach(all ->
                all.getChildren().forEach(children -> {
                            boolean res = chooseCategory.stream().anyMatch(choose -> children.getPid() != 0 && choose.getCategoryId().equals(children.getId()));
                            children.setChoose(res);
                            if (res && Objects.isNull(all.getChoose())) {
                                all.setChoose(true);
                            }

                        }
                )

        );
        return thirdCategoryPage;
    }

    @Override
    public Integer deleteByCIdAndPIds(Long categoryId, Long[] ids) {
        return baseDao.delete(new LambdaQueryWrapper<ProductCategoryMappingEntity>()
                .eq(ProductCategoryMappingEntity::getCategoryId, categoryId)
                .in(ProductCategoryMappingEntity::getProductId, Arrays.asList(ids)));
    }

    @Override
    public void deleteByPIds(List<Long> pIds) {
        baseDao.delete(new LambdaQueryWrapper<ProductCategoryMappingEntity>().in(ProductCategoryMappingEntity::getProductId, pIds));
    }

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void autoMappingByTag(ProductEntity productEntity) {
//        String tag = productEntity.getTag();
//        List<CategoryEntity> list = new ArrayList<>();
//
//        if (StringUtils.isNotBlank(tag)) {
//            // 根据第三方类名构建查询条件
//            List<String> strings = Arrays.stream(tag.split(Constant.SYMBOL_SLASH))
//                    .filter(StringUtils::isNotBlank)
//                    .collect(Collectors.toList());
//            LambdaQueryWrapper<CategoryEntity> wrapper = new LambdaQueryWrapper<>();
//            wrapper.ne(CategoryEntity::getPid, 0L)
//                    .and(w -> {
//                        for (int i = 0; i < strings.size(); i++) {
//                            if (i != 0) {
//                                w.or();
//                            }
//                            w.like(CategoryEntity::getThirdName, strings.get(i));
//                        }
//                    });
//            list = categoryService.list(wrapper);
//        }
//
//
//        if (CollectionUtils.isEmpty(list)) {
//            // 如果找不到统一分到非标准类
//            CategoryEntity categoryEntity = new CategoryEntity();
//            categoryEntity.setId(1581952378456788994L);
//            list.add(categoryEntity);
//        }
//
//        // 封装映射实体集合
//        List<ProductCategoryMappingEntity> mappingEntityList = list.stream().map(item -> {
//            ProductCategoryMappingEntity productCategoryMappingEntity = new ProductCategoryMappingEntity();
//            productCategoryMappingEntity.setProductId(productEntity.getId());
//            productCategoryMappingEntity.setCategoryId(item.getId());
//            return productCategoryMappingEntity;
//        }).collect(Collectors.toList());
//
//
//        // 批量保存映射并返回结果
//        try {
//            this.insertBatchOwn(mappingEntityList);
//        } catch (Exception e) {
//            log.error("关联分类失败:{}", JSON.toJSONString(productEntity), e);
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//        }
//    }

    @Override
    public Integer deleteByPIdAndCIds(Long productId, Long[] ids) {
        return baseDao.delete(new LambdaQueryWrapper<ProductCategoryMappingEntity>()
                .eq(ProductCategoryMappingEntity::getProductId, productId)
                .in(ProductCategoryMappingEntity::getCategoryId, Arrays.asList(ids)));
    }

    @Override
    public void autoMappingProductCategoryByProductId(Long productId) {
        try {
            autoMappingProductCategory(productId);
        } catch (BusinessException e) {
            log.error("手动映射PPT分类异常，id={}", productId, e);

            ThirdProductEntity thirdProductEntity = thirdProductService.getOne(new LambdaQueryWrapper<ThirdProductEntity>()
                    .eq(ThirdProductEntity::getResId, productId));

            if (Objects.isNull(thirdProductEntity)) {
                log.error("找不到三方商品记录！！！");
                return;
            }

            thirdProductEntity.setStatus(ThirdResStatusEnum.ERROR.getCode());
            thirdProductEntity.setStatusMsg(StringUtil.subString("手动映射PPT分类异常：" + e.getMessage(), 0, 2000));

            thirdProductService.updateById(thirdProductEntity);
        }
    }

    private void autoMappingProductCategory(Long productId) {
        // 根据己方商品主键ID，查询数据
        ProductEntity productEntity = productService.getById(productId);

        if (Objects.isNull(productEntity)) {
            throw new BusinessException("找不到己方商品记录");
        }

        // 根据己方商品主键ID，查询第三方商品主键Id
        ThirdProductEntity thirdProductEntity = thirdProductService.getOne(new LambdaQueryWrapper<ThirdProductEntity>()
                .eq(ThirdProductEntity::getResId, productId));

        if (Objects.isNull(thirdProductEntity)) {
            throw new BusinessException("找不到三方商品记录");
        }

        // 根据第三方商品主键ID，查询第三方商品所属的第三方分类集合
        List<ThirdProductCategoryMappingEntity> thirdProductCategoryMappingList = thirdProductCategoryMappingService.list(new LambdaQueryWrapper<ThirdProductCategoryMappingEntity>()
                .eq(ThirdProductCategoryMappingEntity::getProductId, thirdProductEntity.getId()));

        if (CollectionUtils.isEmpty(thirdProductCategoryMappingList)) {
            throw new BusinessException("三方商品未关联三方分类");
        }
        List<Long> thirdCategoryIds = thirdProductCategoryMappingList.stream().map(ThirdProductCategoryMappingEntity::getCategoryId).collect(Collectors.toList());

        // 根据第三方商品所属的第三方分类集合，查询己方的分类
        List<ThirdCategoryMappingEntity> selfCategoryList = thirdCategoryMappingService.list(new LambdaQueryWrapper<ThirdCategoryMappingEntity>()
                .in(ThirdCategoryMappingEntity::getThirdCategoryId, thirdCategoryIds));

        if (CollectionUtils.isEmpty(selfCategoryList)) {
            throw new BusinessException("不存在关联分类映射");
        }

        Set<Long> selfCategoryIds = selfCategoryList.stream().map(ThirdCategoryMappingEntity::getCategoryId).collect(Collectors.toSet());

        // 构建映射己方分类实体
        List<ProductCategoryMappingEntity> mappingList = selfCategoryIds.stream().map(categoryId -> {
            ProductCategoryMappingEntity mappingEntity = new ProductCategoryMappingEntity();
            mappingEntity.setProductId(productEntity.getId());
            mappingEntity.setCategoryId(categoryId);
            return mappingEntity;
        }).collect(Collectors.toList());

        // 查询已存在的分类
        List<ProductCategoryMappingEntity> existCategoryList = productCategoryMappingService.list(new LambdaQueryWrapper<ProductCategoryMappingEntity>()
                .in(ProductCategoryMappingEntity::getCategoryId, selfCategoryIds)
                .eq(ProductCategoryMappingEntity::getProductId, productEntity.getId()));

        // 过滤掉已存在的分类
        List<ProductCategoryMappingEntity> newCategoryList = mappingList.stream()
                .filter(oldItem ->
                        existCategoryList.stream().noneMatch(newItem ->
                                newItem.getCategoryId().equals(oldItem.getCategoryId())))
                .collect(Collectors.toList());

        // 已存在过分类
        if (CollectionUtils.isEmpty(newCategoryList)) {
            return;
        }

        log.info("新增关联 pId={},cIds={}", productId, newCategoryList);
        // 保存
        boolean mappingSaveRes = productCategoryMappingService.saveBatch(newCategoryList);
        if (!mappingSaveRes) {
            throw new BusinessException("商品分类映射返回失败");
        }
    }
}




